package com.servlet;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.service.QRCodeMaker;
import com.service.QRService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Hashtable;
import java.util.UUID;

/**
 * Created by ztc on 16-3-21.下午2:14
 */
public class QRCoder extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            HttpSession session=request.getSession();
            if(session.getAttribute("recordCount")!=null) {
                int count = (Integer)session.getAttribute("recordCount");
                session.setAttribute("recordCount", ++count);
                System.out.println("count: " + count);
            }else {
                session.setAttribute("recordCount",1);
                System.out.println("count: 1" );
            }
            String uuid=UUID.randomUUID().toString();
            String teacherID=request.getParameter("teacherID");
            String myurl="http://192.168.43.250:8080/qrsiginin?uuid="+uuid
                    +"&teacherID="+teacherID
                    +"&stuID="+"1231231"
                    +"&stuName="+"name"
                    +"&count="+session.getAttribute("recordCount");
			Hashtable<EncodeHintType,String> hints =
                                      new Hashtable<EncodeHintType,String>();
        // 内容所使用编码
        	hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix b=new MultiFormatWriter().encode(
                    myurl, BarcodeFormat.QR_CODE,177,177,hints);
            new QRCodeMaker().writeToStream(b, response.getOutputStream(), "gif");
            new QRService().insertInto(uuid,teacherID);



        } catch (WriterException e) {
            e.printStackTrace();
        }
    }
}
